package jwt

import (
	"github.com/golang-jwt/jwt/v5"
	"regexp"
	"time"
)

const (
	//AUTH   header
	AUTH = "Authorization"
)

type JWT struct {
	key     []byte
	TimeOut int64
}
type MyCustomClaims struct {
	UserId int64
	jwt.RegisteredClaims
}

func NewJwt(secret string, timeout int64) *JWT {
	return &JWT{
		key:     []byte(secret),
		TimeOut: timeout,
	}
}

func (j *JWT) GenToken(userId int64, expiresAt time.Time) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, MyCustomClaims{
		UserId: userId,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(expiresAt),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			NotBefore: jwt.NewNumericDate(time.Now()),
			Issuer:    "",
			Subject:   "",
			ID:        "",
			Audience:  []string{},
		},
	})

	// Sign and get the complete encoded jwt as a string using the key
	tokenString, err := token.SignedString(j.key)
	if err != nil {
		return "", err
	}
	return tokenString, nil
}

func (j *JWT) ParseToken(tokenString string) (*MyCustomClaims, error) {
	re := regexp.MustCompile(`(?i)Bearer `)
	tokenString = re.ReplaceAllString(tokenString, "")
	token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		return j.key, nil
	})
	if err != nil {
		return nil, err
	}
	if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
		return claims, nil
	} else {
		return nil, err
	}
}

// GetTokenString 获取原始token字符串 不带Bearer
func (j *JWT) GetTokenString(token string) string {
	re := regexp.MustCompile(`(?i)Bearer `)
	return re.ReplaceAllString(token, "")
}
func (j *JWT) GetUserId(token string) (int64, error) {
	Claims, err := j.ParseToken(token)
	if err != nil {
		return 0, err
	}
	return Claims.UserId, nil
}
